//
//  RecommendController.m
//  Mango
//
//  Created by lanou3g on 16/5/5.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "RecommendController.h"
#import "BaseModel.h"
#import "BaseCell.h"
#import "DetailViewController.h"
#import "VideoCell.h"
#import "CWCycleView.h"
#import "GifCell.h"
#import "FullPlayViewController.h"
#import "UMSocial.h"
#import "VideoPlayView.h"
#define RecommendUrl @"http://api.app.happyjuzi.com/article/list/home"


@interface RecommendController ()<VideoCellDelegate,GifCellDelegate,VideoPlayViewDelegate,VideoCellDelegate>
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSMutableArray *infoID;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) CWCycleView *cycleView;
@property (nonatomic, strong) NSMutableArray *urlRoutes;
@property (nonatomic, assign) NSIndexPath *gifIndexPath;
@property (nonatomic, assign) BOOL isFullScreenPlaying;
@property (nonatomic, strong) VideoCell *currentSelectedCell;


@property (nonatomic, strong) FullPlayViewController *fullVc;
@property (nonatomic, weak) VideoPlayView *playView;
@property (nonatomic, copy) NSString *currentSkinModel;//夜间模式
@end

@implementation RecommendController

#pragma mark - 懒加载代码
- (FullPlayViewController *)fullVc
{
    if (_fullVc == nil) {
        self.fullVc = [[FullPlayViewController alloc] init];
    }
    return _fullVc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataSource = [NSMutableArray new];
    self.infoID = [NSMutableArray new];
    self.cycleView = [[CWCycleView alloc]initWithFrame:CGRectMake(0, 0, ScreenSizeW, ScreenSizeW * 562 / 750 + 5 + 40) Interval:2.5];
    //轮播图点击跳转
    __weak typeof(self)weakSelf = self;
    [self.cycleView addTapBlock:^(NSInteger index) {
        NSString *url = weakSelf.urlRoutes[index];
        if ([url isEqualToString:@"juzi://specialreport"]) {
            return ;
        }
        DetailViewController *detailVC = [[DetailViewController alloc]init];
        detailVC.ID = [weakSelf.infoID[index]integerValue];
        [weakSelf.navigationController pushViewController:detailVC animated:YES];
    }];
    self.tableView.tableHeaderView = self.cycleView;
    
    //注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"LeftModelCell" bundle:nil] forCellReuseIdentifier:@"LeftModel"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TopModelCell" bundle:nil] forCellReuseIdentifier:@"TopModel"]
    ;
    [self.tableView registerNib:[UINib nibWithNibName:@"VideoCell" bundle:nil] forCellReuseIdentifier:@"VideoModel"];
    [self.tableView registerNib:[UINib nibWithNibName:@"GifCell" bundle:nil] forCellReuseIdentifier:@"GifModel"];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor colorWithRed:223/255.0 green:223/255.0 blue:223/255.0 alpha:0.7];
    
    [self refreshData];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSkinModel) name:SkinModelDidChangedNotification object:nil];
    [self updateSkinModel];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark --private Method--更新皮肤模式 接到模式切换的通知后会调用此方法
-(void)updateSkinModel {
    self.currentSkinModel = [[NSUserDefaults standardUserDefaults] stringForKey:CurrentSkinModelKey];
    if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {//夜间模式
        self.tableView.backgroundColor = [UIColor blackColor];
        [self.cycleView updateToNightSkinMode];
    } else {//日间模式
        self.tableView.backgroundColor = [UIColor colorWithRed:223/255.0 green:223/255.0 blue:223/255.0 alpha:0.7];
        [self.cycleView updateToDaySkinMode];
    }
    [self.tableView reloadData];
}

//请求网络数据
#pragma mark - 加载数据 刷新数据

- (void)loadDataFromServerWithPage:(NSUInteger)page {
    NSDictionary *paramDict = @{@"uid":@"3971092394255935",@"res":@"1080x1920",@"ver":@"2.11",@"startup":@1,@"pf":@"android",@"channel":@"yingyongbao",@"accesstoken":@"e43c576b3de11eeeb758223cb56752c1",@"page":@(page),@"net":@"wifi"};
    
    [[AFHTTPSessionManager manager]GET:RecommendUrl parameters:paramDict progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dataDic = responseObject[@"data"];
        if (page == 1) {
            [self.dataSource removeAllObjects];
            //头条
            NSMutableArray *imgUrlArray = [NSMutableArray new];
            NSMutableArray *titles = [NSMutableArray new];
            for (NSDictionary *dict in dataDic[@"info"]) {
                NSString *imgUrl = [dict[@"pic"] componentsSeparatedByString:@"!"][0];
                [imgUrlArray addObject:imgUrl];
                NSString *title = dict[@"title"];
                [titles addObject:title];
                NSInteger ID = [dict[@"id"]integerValue];;
                [self.infoID addObject:@(ID)];
                NSString *url = [dict[@"urlroute"] componentsSeparatedByString:@"?"][0];
                [self.urlRoutes addObject:url];
            }
            self.cycleView.titles = titles;//先赋值
            self.cycleView.imgUrlArray = imgUrlArray;
        }
        
        //每页列表
        for (NSDictionary *itemDic in dataDic[@"list"]) {
            BaseModel *baseModel = [BaseModel baseModelWithDictionary:itemDic];
            if (baseModel.pic) {
                [self.dataSource addObject:baseModel];
            }
        }
//        NSLog(@"%@",self.dataSource);
        [self.tableView reloadData];
        
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

//添加刷新
- (void)refreshData {
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}
//获取新数据
- (void)loadNewData {
    self.page = 1;
    [self loadDataFromServerWithPage:self.page];
}
//加载更多数据
- (void)loadMoreData {
    self.page++;
    [self loadDataFromServerWithPage:self.page];
}




#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return self.dataSource.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BaseCell *cell = [BaseCell cellWithTableView:tableView andIndexPath:indexPath andModel:self.dataSource[indexPath.row]];
    if ([cell isKindOfClass:[GifCell class]]) {
        GifCell *gifCell = (GifCell *)cell;
        gifCell.delegate = self;
        gifCell.indexPath = indexPath;
    }
    if ([cell isKindOfClass:[VideoCell class]]) {
        VideoCell *videoCell = (VideoCell *)cell;
        videoCell.delegate = self;
        videoCell.indePath = indexPath;
    }
    
#pragma mark --private Method--更新皮肤模式
    if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {//日间模式
        [cell updateToNightSkinMode];
    }else {
        [cell updateToDaySkinMode];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

#pragma mark VideoTableViewCell的代理方法
-(void)clickVideoButton:(NSIndexPath *)indexPath {
    
    [self.playView resetPlayView];
    
    VideoCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    self.currentSelectedCell = cell;
    VideoPlayView *playView = [VideoPlayView videoPlayView];
    VideoModel *video = self.dataSource[indexPath.row];
    playView.frame = video.videoFrame;
    [cell addSubview:playView];
    self.playView = playView;
    self.playView.delegate = self;
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:video.src]];
    self.playView.playerItem = item;
}

#pragma mark - videoPlayView代理方法
- (void)videoplayViewSwitchOrientation:(BOOL)isFull
{
    if (isFull) {
        self.isFullScreenPlaying = YES;
        [self presentViewController:self.fullVc animated:YES completion:^{
            self.playView.frame = self.fullVc.view.bounds;
            [self.fullVc.view addSubview:self.playView];
             self.playView.closeBtn.hidden = YES;
        }];
    } else {
        [self.fullVc dismissViewControllerAnimated:YES completion:^{
            self.playView.frame = self.currentSelectedCell.model.videoFrame;
            [self.currentSelectedCell addSubview:self.playView];
            self.isFullScreenPlaying = NO;
             self.playView.closeBtn.hidden = NO;
        }];
    }
}

#pragma mark - gifCellDelegate
- (void)gifCellDidClickGifBtn:(NSIndexPath *)indexPath {
    self.gifIndexPath = indexPath;
}

- (void)gifCellDidClickShareBtn:(GifModel *)model {
    //构造分享内容
    NSString *imgUrlStr = [model.pic componentsSeparatedByString:@"!"][0];
    [[UMSocialData defaultData].urlResource setResourceType:UMSocialUrlResourceTypeImage url:imgUrlStr];
    //    [UMSocialData defaultData].extConfig.title = model.title;
    [UMSocialData defaultData].shareText = model.title;
    [UMSocialData defaultData].shareImage = imgUrlStr;
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:@"sina"];
    snsPlatform.snsClickHandler(self,[UMSocialControllerService defaultControllerService],YES);
}

//判断是否滚出屏幕
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (![self.tableView.indexPathsForVisibleRows containsObject:self.gifIndexPath]) {
        GifCell *cell = [self.tableView cellForRowAtIndexPath:self.gifIndexPath];
        [cell resetImageView];
    }
    NSIndexPath *indexPath = [self.tableView indexPathForCell:self.currentSelectedCell];
    if (![self.tableView.indexPathsForVisibleRows containsObject:indexPath]) {
        [self.playView resetPlayView];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    BaseModel *model = self.dataSource[indexPath.row];
    return model.cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    BaseModel *model = self.dataSource[indexPath.row];
    if ([model isKindOfClass:[GifModel class]]) {
        return;
    }
    NSString *urlRoute = [model.urlroute componentsSeparatedByString:@"?"][0];
    if ([urlRoute isEqualToString:@"juzi://specialreport"]) {
        return;
    }
    DetailViewController *detailVC = [[DetailViewController alloc]init];
    detailVC.ID = model.ID;
    detailVC.listmodel = model;
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if (self.view.window == nil && [self isViewLoaded]) {
        self.view = nil;
    }
}
@end
